package com.sharp.authorization.dao.common.repository;

import com.sharp.authorization.dao.common.entity.AcRole;
import com.sharp.authorization.dao.common.mapper.AcRoleDao;
import com.sharp.kernel.constant.db.SqlConstant;
import com.sharp.kernel.mybatis.repository.BaseMysqlRepository;
import com.sharp.kernel.utils.ReflectionUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Title: AcRoleService
 * Description: Copyright: Copyright (c) 2019 Company: BHFAE
 *
 * @author Sharp
 * @date 2022/6/14 17:48
 */
@Service
public class AcRoleService extends BaseMysqlRepository<AcRole, AcRoleDao> {

    @Resource
    private AcRoleDao acRoleDao;

    public List<AcRole> getRoleByParentRoleId(String roleId) {
        Example example = getExample();
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo(SqlConstant.VALID_FIELD, SqlConstant.VALID);
        criteria.andEqualTo("parentRoleId", roleId);
        return super.select(example);
    }

    public List<AcRole> getRoleByParentRoleName(String parentRoleName) {
        return getRoleByParentRoleName(null, parentRoleName);
    }

    public List<AcRole> getRoleByParentRoleName(String roleName, String parentRoleName) {
        if (StringUtils.isBlank(parentRoleName)) {
            return getRoleByRoleName(roleName);
        }
        List<AcRole> roles = getRoleByRoleName(parentRoleName);
        List<Integer> parentRoleIdList = ReflectionUtil.getFieldList(roles, "id", Integer.class);
        if (CollectionUtils.isEmpty(parentRoleIdList)) {
            return new ArrayList<>();
        }
        Example example = getExample();
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo(SqlConstant.VALID_FIELD, SqlConstant.VALID);
        criteria.andIn("parentRoleId", parentRoleIdList);
        if (StringUtils.isNotBlank(roleName)) {
            criteria.andEqualTo("name", roleName);
        }
        return super.select(example);
    }

    public List<AcRole> getRoleByRoleName(String roleName) {
        Example example = getExample();
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo(SqlConstant.VALID_FIELD, SqlConstant.VALID);
        if (StringUtils.isNotBlank(roleName)) {
            criteria.andEqualTo("name", roleName);
        }
        return super.select(example);
    }

    public AcRole getOneRoleByRoleName(String roleName) {
        Example example = getExample();
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo(SqlConstant.VALID_FIELD, SqlConstant.VALID);
        if (StringUtils.isNotBlank(roleName)) {
            criteria.andEqualTo("name", roleName);
        }
        return super.selectOne(example);
    }
}

